package org.net5ijy.cloud.plugin.feign;

import static org.net5ijy.cloud.plugin.feign.core.FeignClassAndModelResolver.resolveFeignClientClassList;
import static org.net5ijy.cloud.plugin.feign.core.FeignClassAndModelResolver.resolveFeignModelList;
import static org.net5ijy.cloud.plugin.feign.core.util.HttpUtil.request;

import com.alibaba.fastjson.JSON;
import org.net5ijy.cloud.plugin.feign.core.model.FeignClassAndModel;
import org.net5ijy.cloud.plugin.feign.core.model.FeignClientClass;
import org.net5ijy.cloud.plugin.feign.core.model.FeignModel;
import org.net5ijy.cloud.plugin.feign.core.util.ZipUtil;
import org.net5ijy.cloud.plugin.feign.core.util.ZipUtil.LocalFileOutputStreamHandler;
import org.net5ijy.cloud.plugin.feign.core.util.ZipUtil.Text;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * FeignClassSendUtil
 *
 * @author XGF
 * @date 2020/11/17 16:10
 */
class FeignClassSendUtil {

  static void serializeAndSend(FeignClassAndModel feignClassAndModel) throws IOException {

    FeignAutoGenerator.log.info("Start send feign class and model metadata");

    String jsonString = JSON.toJSONString(feignClassAndModel);

    Map<String, String> headers = new HashMap<>(1);

    String response = request(FeignAutoGenerator.manageServer, jsonString, headers);

    FeignAutoGenerator.log.info("Send feign client metadata response: " + response);
  }

  static void localSave(String localPath,boolean isOver,FeignClassAndModel feignClassAndModel)
      throws IOException, TemplateException {

    List<Text> pathAndFileContents = new ArrayList<>();

    List<FeignClientClass> feignClientClasses = feignClassAndModel.getFeignClientClasses();
    List<FeignModel> feignModels = feignClassAndModel.getFeignModels();

    pathAndFileContents.addAll(resolveFeignClientClassList(feignClassAndModel.getBasePackage(),feignClientClasses));
    pathAndFileContents.addAll(resolveFeignModelList(feignModels));


    if(localPath == null || localPath.equals("")) {
      FeignAutoGenerator.log.info("Start save feign class and model metadata to project/target(zip)");
      String path = FeignAutoGenerator.mavenProject.getBasedir() + "/target/"
              + FeignAutoGenerator.mavenProject.getArtifactId() + "-feign-src.zip";

      ZipUtil.zipTexts(
              pathAndFileContents,
              new LocalFileOutputStreamHandler(path));
    }else{
      String   path =   localPath;

      FeignAutoGenerator.log.info("Start save feign class and model metadata to :"+path);

      pathAndFileContents.forEach(t->{
        File file = new File(path+"/"+t.getFileName());

        createDirIfUnexists(file.getParent());

        try {
          // if file doesn't exists, then create it
          if (!file.exists()) {
            file.createNewFile();
          } else {
            if (isOver) {
              FeignAutoGenerator.log.info("over file :" + file.getAbsolutePath());
              file.delete();
              file.createNewFile();
            } else {
              FeignAutoGenerator.log.info("skip file :" + file.getAbsolutePath());
              return;
            }
          }
        }catch (IOException e){
            e.printStackTrace();
        }

        //System.out.println(t.getFileName()+"==="+file.getAbsolutePath());
        try (FileOutputStream fop = new FileOutputStream(file)) {
          // get the content in bytes
          byte[] contentInBytes = t.getText().getBytes("UTF-8");
          fop.write(contentInBytes);
          fop.flush();

        } catch (IOException e) {
          e.printStackTrace();
        }

      });

    }

  }

  /**
   * 创建文件夹（目录），存在不可覆盖
   * @param destDirName 创建路径（D:/com/filePath）
   * @return
   */
  static  boolean createDirIfUnexists(String destDirName) {

    File dir = new File(destDirName);
    if (dir.exists()) {
     // System.out.println("创建目录" + destDirName + "失败，目标目录已存在！");
      return false;
    }
    if (!destDirName.endsWith(File.separator)) {
      destDirName = destDirName + File.separator;
    }
    // 创建单个目录
    if (dir.mkdirs()) {
      //System.out.println("创建目录" + destDirName + "成功！");
      return true;
    } else {
      //System.out.println("创建目录" + destDirName + "成功！");
      return false;
    }
  }
}
